package io.wdb.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = WxDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "wxSqlSessionFactory")
public class WxDataSourceConfig {

    static final String PACKAGE = "io.wdb.modules.activity.*.dao";
    static final String MAPPER_LOCATION = "classpath:mapper/activity/*/*.xml";

    @Value("${spring.datasource.druid.url_biz}")
    private String url;

    @Value("${spring.datasource.druid.username_biz}")
    private String user;

    @Value("${spring.datasource.druid.password_biz}")
    private String password;

    @Value("${spring.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "wxDataSource")
    public DataSource wxDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "wxTransactionManager")
    public DataSourceTransactionManager wxTransactionManager() {
        return new DataSourceTransactionManager(wxDataSource());
    }

    @Bean(name = "wxSqlSessionFactory")
    public SqlSessionFactory wxSqlSessionFactory(@Qualifier("wxDataSource") DataSource wxDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(wxDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(WxDataSourceConfig.MAPPER_LOCATION));
        
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }
}